/**
 * File:   NetNodeModel.java
 * Author: Gvennet
 */
package scenarios.net;

import dht.identifier.identifier.Identifier;

import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * todo write javadoc
 */
public final class NetNodeModel
{

	private final List<NetNodeRow> nodes;

	private final List<NetNodeEventListener> listenerList;

	public NetNodeModel()
	{
		nodes = new LinkedList<NetNodeRow>();
		listenerList = new CopyOnWriteArrayList<NetNodeEventListener>();
	}

	public void put(NetNodeRow nodeRow)
	{

		nodes.add(nodeRow);
		fireRowInserted(nodeRow);
	}

	public boolean update(Identifier id, int port, boolean active)
	{
		boolean result = false;
		boolean label = true;

		NetNodeRow tempRow = null;
		for (NetNodeRow row : nodes)
		{
			tempRow = row;
			if (tempRow.getId().compareTo(id) == 0)
			{
				tempRow.setActive(active);
				fireRowUpdated(tempRow);
				label = false;
				break;
			}
		}
		if (label)
		{
			tempRow = new NetNodeRow(id, port, active);
			nodes.add(tempRow);
			fireRowInserted(tempRow);
			result = true;
		}


		return result;
	}

	public boolean contains(Identifier id)
	{

		for (NetNodeRow nodeRow : nodes)
		{
			if (nodeRow.getId().compareTo(id) == 0)
			{
				return true;
			}
		}
		return false;
	}

	public List<NetNodeRow> getNodes()
	{
		return new LinkedList<NetNodeRow>(nodes);
	}

	public int getSize()
	{
		return nodes.size();
	}

	public int getPort(int i)
	{

		return nodes.get(i).getPort();
	}

	public void remove(int i)
	{
		NetNodeRow tempRow = nodes.get(i);
		nodes.remove(i);
		fireRowRemoved(tempRow);
	}

	public void addListener(NetNodeEventListener listener)
	{
		listenerList.add(listener);
	}

	public void removeListener(NetNodeEventListener listener)
	{
		listenerList.remove(listener);
	}

	private void fireRowInserted(NetNodeRow nodeRow)
	{
		for (NetNodeEventListener aListenerList : listenerList)
		{
			aListenerList.rowAdded(nodeRow);
		}
	}

	private void fireRowRemoved(NetNodeRow nodeRow)
	{
		for (NetNodeEventListener aListenerList : listenerList)
		{
			aListenerList.rowRemoved(nodeRow);
		}
	}

	private void fireRowUpdated(NetNodeRow nodeRow)
	{
		for (NetNodeEventListener aListenerList : listenerList)
		{
			aListenerList.rowUpdated(nodeRow);
		}
	}
}